package com.yanqu.road.server.manager.activity.suitang.activity;

import com.google.protobuf.AbstractMessage;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.suitang.config.*;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangStage;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangTaskType;
import com.yanqu.road.entity.activity.tongbing.config.TongBingConfig;
import com.yanqu.road.entity.enums.eTongBingTaskType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.activity.suitang.SuiTangMapLogic;
import com.yanqu.road.logic.bussiness.activity.SuiTangActivityBusiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.TongBingProto;
import com.yanqu.road.pb.server.ServerProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.suitang.task.BaseCrossSuiTangTask;
import com.yanqu.road.server.manager.activity.tongbing.activity.CrossTongBingBaseActivity;
import com.yanqu.road.server.manager.activity.tongbing.task.BaseCrossTongBingTask;
import com.yanqu.road.server.manager.scene.CrossSceneMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.AgentProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.DelayQueue;

public class CrossSuiTangBaseActivity {

    protected static Logger logger = LogManager.getLogger(CrossSuiTangBaseActivity.class.getName());

    /**
     * 大锁
     */
    protected final Object lock = new Object();

    /**
     * 活动配置
     */
    protected SuiTangConfigSync config;

    // ============================== 停线程 ==============================

    private boolean isStop = false;

    public void setStop(boolean stop) {
        isStop = stop;
    }

    // ============================== 定时器 ==============================

    /**
     * 单独线程
     */
    protected Thread thread = new Thread(new DelayQueueRun());

    protected class DelayQueueRun implements Runnable {
        @Override
        public void run() {
            while (true) {

                if (isStop) {
                    return;
                }

                try {
                    BaseCrossSuiTangTask task = taskQueue.take();

                    // 活动结束的任务：
                    if (task.getBeginTime() > config.getActivityInfo().getEndTime() * 1000L) {
                        if (task.getType() != eSuiTangTaskType.SetWinner
                                && task.getType() != eSuiTangTaskType.SendUnionHonor
                                && task.getType() != eSuiTangTaskType.MainTask
                        && (task.getType() != eSuiTangTaskType.AutoBattle || config.getSuiTangStage().getValue() > eSuiTangStage.WaitRewardTime.getValue())) {
                            continue;
                        }
                    }

                    // 正常执行
                    try {
                        task.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (!task.isOnce()) {
                            task.setBeginTime(task.getFinishTime() + task.getRunnableTime());
                            addTask(task);
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 定时器执行队列
     */
    protected DelayQueue<BaseCrossSuiTangTask> taskQueue = new DelayQueue<>();

    /**
     * 添加task，随便加，使用时会再校验时间
     */
    public void addTask(BaseCrossSuiTangTask task) {
        if (!task.isOnce() && haveTask(task)) {
            // 循环任务不要重复加了
            logger.warn("sui tang addTask already have task : {}", task.getType().name());
            return;
        }
        if (haveOnceTask(task)) {
            return;
        }
        taskQueue.add(task);
    }

    public void AllTask() {
        for (BaseCrossSuiTangTask taskTemp : taskQueue) {
            logger.debug("suitang task:{}", taskTemp.getType().name());
        }
    }

    /*
     * 是有拥有任务
     */
    public boolean haveTask(BaseCrossSuiTangTask task) {
        for (BaseCrossSuiTangTask taskTemp : taskQueue) {
            if (taskTemp.getType() == task.getType() && task.getId().equals(taskTemp.getId())) {
                return true;
            }
        }
        return false;
    }

    public boolean haveOnceTask(BaseCrossSuiTangTask task) {
        for (BaseCrossSuiTangTask taskTemp : taskQueue) {
            if (taskTemp.getType() == task.getType() && task.getId().equals(taskTemp.getId()) && task.getBeginTime() == taskTemp.getBeginTime()) {
                return true;
            }
        }
        return false;
    }

    protected CrossSuiTangBaseActivity(ActivityInfo activityInfo) {
        CrossSceneMgr.initActivity(activityInfo);
        // 读配置
        loadConfigFromDb(activityInfo);
    }

    public SuiTangConfigSync getConfig() {
        return config;
    }

    /**
     * 数据库加载配置
     */
    public void loadConfigFromDb(ActivityInfo activityInfo) {
        if (activityInfo == null) {
            return;
        }
        int activityId = activityInfo.getActivityId();
        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(Collections.singletonList(activityInfo.getActivityId())).get(activityInfo.getActivityId());

        SuiTangConfigSync tmpConfig = new SuiTangConfigSync();
        tmpConfig.setActivityId(activityId);
        tmpConfig.setActivityInfo(activityInfo);
        tmpConfig.setBuffConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangBuffConfig.class));
        tmpConfig.setCityConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangCityConfig.class));
        tmpConfig.setCityTypeConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangCityTypeConfig.class));
        tmpConfig.setRankConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangRankConfig.class));
        tmpConfig.setGuessConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangGuessConfig.class));
        tmpConfig.setActivityConfigMap(activityConfigMap);
        tmpConfig.getParamConfig().initParamConfig(activityConfigMap);
        tmpConfig.setCityConnectMap(SuiTangMapLogic.getCityConnectMapConfig());
        tmpConfig.calcTimeList();
        tmpConfig.calcCampBoxConfig();
        config = tmpConfig;
    }

    public Object getLock() {
        return lock;
    }



    public int calcRoundMain() {
        return Math.min(Math.max(0, DateHelper.calc2DateTDOADays(new Date(config.getActivityInfo().getBeginTime() * 1000), new Date()) - 1), 3);
    }


    // ============================== 发消息 ==============================

    public void sendPacket(int code, AbstractMessage.Builder<?> messageBuilder, long userId) {
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
        if (userBaseInfo == null) {
            return;
        }
        YanQuMessage message = YanQuMessageUtils.buildMessage(code, messageBuilder);
        MessageHelper.sendPacket(userBaseInfo.getServerId(), userId, message);
    }

    public void sendPacketToAll(int code, AbstractMessage.Builder<?> messageBuilder, Collection<Long> userIdList) {
        MessageHelper.sendPacketToAll(code, messageBuilder, userIdList);
    }
}
